/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package syslivros;

import java.awt.HeadlessException;
import java.awt.event.KeyEvent;
import java.io.FileNotFoundException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Rafael
 */
public class Consultar_Base extends javax.swing.JFrame {
public static ArrayList<StringBuilder> linhas;
    /**
     * Creates new form Consultar_Base
     */
    public Consultar_Base() {
        initComponents();
         try {
                Conexao.conectar("root", "positivo");
                System.out.println("conetado!ура товарищи!");
                
            } catch (Exception ex) {
               JOptionPane.showMessageDialog(null,"Erro ao conectar ao banco"+ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
            } 
        
        try {
            PopulaComboCurso();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this,"Erro ao carrgar o comboBox"+ ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
        }
    }
    public void PopulaComboCurso()throws  SQLException{
String SQL="select NomeCurso  from listacursos  ";
ResultSet rs = Conexao.ConexaoJDBC.createStatement().executeQuery(SQL);
   DefaultComboBoxModel model =(DefaultComboBoxModel) cbApostila.getModel();
   model.removeAllElements();
   while(rs.next()){
   model.addElement(rs.getString("NomeCurso"));
   }

}

    public void consultar() {
        DefaultTableModel model = (DefaultTableModel) table_consulta.getModel();
        model.setRowCount(0);
        String Apostila = (String) cbApostila.getSelectedItem();
       // String Local = (String) cbLocal.getSelectedItem();
        String SQL = "SELECT * FROM historico_base"
                +" WHERE lower(nm_Curso)"
               
                +" LIKE '%"+Apostila.toLowerCase()+"%'";
                
        try {
            Statement stmt = Conexao.ConexaoJDBC.createStatement();

            try {
                try (ResultSet rs = stmt.executeQuery(SQL)) {
                    while (rs.next()) {
                        model.addRow(new Object[]{
                                    rs.getInt("IdHistorico_base"), rs.getString("nm_curso")
                                ,rs.getString("qt_apostila"),rs.getDate("dt_data_Entrada")});
                    }
                    linhas = new ArrayList<>();
                    StringBuilder b;
                    for (int i = 0; i < table_consulta.getRowCount(); i++) {
                        b = new StringBuilder();
                        for (int j = 0; j < table_consulta.getColumnCount(); j++) {
                            if(j%6==0){
                            b.append(table_consulta.getValueAt(i, j)).append("; \n");
                                    
                            }else{b.append(table_consulta.getValueAt(i, j)).append(" ");
                            }
                        } linhas.add(b);
                       
                    }

                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Erro 1"+ex.getMessage());
            }
        } catch (SQLException | HeadlessException ex2) {
            JOptionPane.showMessageDialog(this, "Erro 2"+ex2.getMessage());


        }
        
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        table_consulta = new javax.swing.JTable();
        lblApostila = new javax.swing.JLabel();
        cbApostila = new javax.swing.JComboBox();
        btnConsultar = new javax.swing.JButton();
        btnVoltar = new javax.swing.JButton();
        btnGerarRelatorio = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Entrada de apostilas ");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        table_consulta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "CURSO", "QUANTIDADE", "DATA DE ENTRADA"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(table_consulta);

        lblApostila.setText("Apostila:");

        cbApostila.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione uma Apostila", ".NET Framework", "Java", "Linux ", "Windows Server" }));

        btnConsultar.setText("Consultar");
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });

        btnVoltar.setText("Voltar");
        btnVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVoltarActionPerformed(evt);
            }
        });
        btnVoltar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnVoltarKeyPressed(evt);
            }
        });

        btnGerarRelatorio.setText("Gerar Relatório");
        btnGerarRelatorio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGerarRelatorioActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnConsultar)
                        .addGap(229, 229, 229)
                        .addComponent(btnGerarRelatorio)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnVoltar)
                        .addGap(18, 18, 18))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblApostila)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cbApostila, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 738, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblApostila)
                    .addComponent(cbApostila, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnConsultar)
                        .addComponent(btnGerarRelatorio))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnVoltar)
                        .addContainerGap())))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-774)/2, (screenSize.height-405)/2, 774, 405);
    }// </editor-fold>//GEN-END:initComponents

    private void btnVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVoltarActionPerformed
       new Consultar().setVisible(true);
       this.dispose();
    }//GEN-LAST:event_btnVoltarActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
 try{
        Conexao.desconectar();
        System.out.println("Desconectado!");
}catch(Exception ex){
JOptionPane.showMessageDialog(this,"Erro ao desconectar o banco"+ ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
}   
    }//GEN-LAST:event_formWindowClosed

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
      try{consultar();
      }catch(Exception ex){
      JOptionPane.showMessageDialog(this,"Erro ao efetuar a consulta"+ ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
      }
    }//GEN-LAST:event_btnConsultarActionPerformed

    private void btnVoltarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnVoltarKeyPressed
if(evt.getKeyCode()==KeyEvent.VK_ENTER){
btnVoltarActionPerformed(null);
}
    }//GEN-LAST:event_btnVoltarKeyPressed

    private void btnGerarRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGerarRelatorioActionPerformed
   try { 
            SysLivros.geraRelatorio_ApostilasRecebidasDOC(linhas);
        } catch (FileNotFoundException ex) {
            System.out.println("ERRO");
        }
    }//GEN-LAST:event_btnGerarRelatorioActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Consultar_Base.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Consultar_Base.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Consultar_Base.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Consultar_Base.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Consultar_Base().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConsultar;
    private javax.swing.JButton btnGerarRelatorio;
    private javax.swing.JButton btnVoltar;
    private javax.swing.JComboBox cbApostila;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblApostila;
    private javax.swing.JTable table_consulta;
    // End of variables declaration//GEN-END:variables
}
